<?php
class Site_categories extends CI_Model {
    function makeMainMenu() {
        $sql = "SELECT CID,ParentCID,CategoryName,CategoryNameLink
                FROM fl_categories
                WHERE Level < 3
                ORDER BY ParentCID, CID";
        $query = $this->db->query($sql);
        return $query->result_array();
    }

    function getCategoryTreeFromCategory($category) {
        $categoryArray = array();
        $a = 0;

        if (is_numeric($category)) {
            $sql = "SELECT * from fl_categories WHERE CID = $category";
        } else {
            $sql = "SELECT * from fl_categories WHERE CategoryNameLink = '$category'";
        }
        $query = $this->db->query($sql);
        if ($query->num_rows()>0) {
            $row = $query->row_array();
            $categoryArray[$a]['CID']   = $row['CID'];
            $categoryArray[$a]['Title'] = $row['CategoryName'];
            $categoryArray[$a]['Link']  = $row['CategoryNameLink'];

            $rows = 1;
            while ($rows > 0) {
                $sql = "SELECT * from fl_categories WHERE CID = ".$row['ParentCID'];
                $query = $this->db->query($sql); 
                if ($query->num_rows()>0) {
                    $a++;
                    $row = $query->row_array();
                    $rows = 1;

                    $categoryArray[$a]['CID']   = $row['CID'];
                    $categoryArray[$a]['Title'] = $row['CategoryName'];
                    $categoryArray[$a]['Link']  = $row['CategoryNameLink'];
                } else {
                    $rows = 0;
                }
            }
        }

        return array_reverse($categoryArray);
    }

    function getCategoriesUnderCategory($category) {
        if (is_numeric($category)) {
            $sql = "SELECT 
                        C.CID,C.CategoryName,C.CategoryNameLink,
                        (SELECT COUNT(RID) FROM fl_resources R WHERE R.CategoryID = C.CID) AS Resources
                    FROM fl_categories C
                    WHERE C.ParentCID = $category";
        } else {
            $sql = "SELECT CID from fl_categories WHERE CategoryNameLink = '$category'";
            $query = $this->db->query($sql);
            $row = $query->row_array();

            $sql = "SELECT
                        C.CID,C.CategoryName,C.CategoryNameLink,
                        (SELECT COUNT(RID) FROM fl_resources R WHERE R.CategoryID = C.CID) AS Resources
                    FROM fl_categories C
                    WHERE C.ParentCID = ".$row['CID'];
        }
        $query = $this->db->query($sql);
        if ($query->num_rows()>0) {
            return $query->result_array();
        } else {
            return false;
        }
    }
}
?>